package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    //指定过滤器的类型，“pre” “routes” “post” “error”
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //指定过滤器添加位置序号
    @Override
    public int filterOrder() {
        return 6;
    }

    //判断针对当前这次请求，是否要执行过滤代码
    //如果请求item-service，执行全选判断
    //如果请求user或order 直接跳过过滤代码
    @Override
    public boolean shouldFilter() {
        //获得正在调用的服务的 服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/y4tg32t243?token=u45t34

        //得到rquest对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        //接收token参数
        String token = request.getParameter("token");
        //如果token参数不存在，阻止继续调用 直接返回提示
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);
            //返回登录提示
            String json = JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login,没有登录")
                    .toString();
            //ctx.addZuulResponseHeader("Content-Type", "application/json;charser=UTF-8");
            ctx.setResponseBody(json);
        }
        //返回任何数据都无效
        return null;
    }
}
